extends Control

var is_active := false
var progress := 0.0
var direction := 1.0
var indicator_position := 0.0
var target_zones := []
var completed_zones := []
var timer := 15.0
var fishing_timer: Timer

@onready var progress_bar = $Background/ProgressBar
@onready var indicator = $Background/ProgressBar/Indicator
@onready var target_zones_container = $Background/ProgressBar/TargetZones
@onready var timer_label = $Background/TimerLabel

func _ready():
	hide()
	
	# 设置红条宽度为5像素
	indicator.size.x = 5
	
	# 创建计时器
	fishing_timer = Timer.new()
	fishing_timer.wait_time = 0.1
	fishing_timer.timeout.connect(_on_timer_timeout)
	add_child(fishing_timer)

func start_fishing():
	show()
	is_active = true
	progress = 0.0
	direction = 1.0
	indicator_position = 0.0
	completed_zones.clear()
	timer = 15.0
	
	# 创建目标区域
	_create_target_zones()
	
	# 更新说明文字
	_update_instructions()
	
	# 启动计时器
	fishing_timer.start()

func hide_fishing():
	hide()
	is_active = false
	fishing_timer.stop()

func _process(delta):
	if not is_active:
		return
	
	# 更新指示器位置 - 使用更平滑的移动
	indicator_position += direction * 0.5 * delta
	
	if indicator_position >= 1.0:
		indicator_position = 1.0
		direction = -1.0
	elif indicator_position <= 0.0:
		indicator_position = 0.0
		direction = 1.0
	
	# 更新指示器UI位置（红条宽度为5%）
	var bar_width = progress_bar.size.x - indicator.size.x
	indicator.position.x = indicator_position * bar_width
	
	# 更新红条颜色：当覆盖未完成的绿色区域时变为黄色
	var is_over_target = false
	for zone in target_zones:
		if zone["completed"]:
			continue
		
		var red_width = 0.05
		var red_start = indicator_position
		var red_end = indicator_position + red_width
		
		if red_start <= zone["start"] and red_end >= zone["end"]:
			is_over_target = true
			break
	
	indicator.color = Color(1, 1, 0, 1) if is_over_target else Color(1, 0, 0, 1)

func _unhandled_input(event: InputEvent) -> void:
	if not is_active:
		return
	
	if event.is_action_pressed("ui_accept"):  # SPACE键
		_check_hit()

func _check_hit():
	var hit = false
	for zone in target_zones:
		if zone["completed"]:
			continue
		
		# 检查绿色是否完全覆盖红条区域
		# 红条宽度5像素，进度条400像素，相对宽度1.25%
		var red_width = 0.0125  # 5/400 = 5%
		var red_start = indicator_position
		var red_end = indicator_position + red_width
		
		if red_start >= zone["start"] and red_end <= zone["end"]:
			zone["completed"] = true
			completed_zones.append(zone)
			_update_zone_visual(zone)
			hit = true
			break
	
	if hit:
		# 更新说明文字
		_update_instructions()
		
		# 检查是否所有区域都完成
		if completed_zones.size() == target_zones.size():
			_end_fishing(true)

func _create_target_zones():
	# 清除旧的目标区域
	for child in target_zones_container.get_children():
		child.queue_free()
	
	target_zones.clear()
	
	# 创建4个固定宽度的绿色区域，位置随机但避免重叠
	var zone_width = 0.08  # 固定宽度8%
	var zones_created = 0
	var used_positions = []
	
	while zones_created < 4:
		var zone_start = randf_range(0.1, 0.85 - zone_width)
		var zone_end = zone_start + zone_width
		
		# 检查是否与现有区域重叠
		var overlap = false
		for pos in used_positions:
			var existing_start = pos
			var existing_end = pos + zone_width
			if (zone_start < existing_end and zone_end > existing_start):
				overlap = true
				break
		
		if not overlap:
			used_positions.append(zone_start)
			
			var zone = {
				"start": zone_start,
				"end": zone_end,
				"completed": false,
				"color_rect": null
			}
			
			# 创建视觉表示
			var color_rect = ColorRect.new()
			target_zones_container.add_child(color_rect)
			color_rect.color = Color(0.2, 0.8, 0.2, 0.8)  # 更亮的绿色
			color_rect.size = Vector2(zone_width * 400, 30)  # 使用进度条实际宽度400
			color_rect.position = Vector2(zone_start * 400, 0)  # 相对于进度条中心定位
			

			zone["color_rect"] = color_rect
			
			target_zones.append(zone)
			zones_created += 1

func _update_zone_visual(zone):
	if zone["color_rect"]:
		if zone["completed"]:
			zone["color_rect"].color = Color(0.2, 0.9, 0.2, 1.0)
		else:
			zone["color_rect"].color = Color(0.2, 0.8, 0.2, 0.6)

func _on_timer_timeout():
	if not is_active:
		return
	
	timer -= 0.1
	timer_label.text = "%.1f" % timer
	
	if timer <= 0:
		_end_fishing(false)

func _update_instructions():
	var remaining = 4 - completed_zones.size()
	$Background/Instructions.text = "按 SPACE 击中目标区域 (%d/4)" % remaining

func _end_fishing(success: bool):
	is_active = false
	fishing_timer.stop()
	
	# 通知钓鱼管理器
	var fishing_manager = get_node("/root/FishingManager")
	if fishing_manager:
		fishing_manager.end_fishing(success)

func _exit_tree():
	if fishing_timer:
		fishing_timer.queue_free()
